package fictional.GUI;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import fictional.Common.GenderItem;
import fictional.Common.IBL;
import fictional.Common.OccupationItem;
import fictional.Common.OrganizationItem;
import fictional.Common.PlaceItem;
import fictional.Common.PowerItem;
import fictional.Common.Response;
import fictional.Common.SpeciesItem;

/**
 * A popup where the logged in user can edit their information. 
 */
@SuppressWarnings("serial")
public class EditInfoPopup extends javax.swing.JFrame {

	IBL BL;
	GUI gui;
	List<GenderItem> genders;
	List<SpeciesItem> species;
	List<PlaceItem> birthPlaces;

    public EditInfoPopup(final GUI gui, IBL BL, GenderItem gender, SpeciesItem species, ArrayList<OrganizationItem> organizations, PlaceItem birthPlace, ArrayList<OccupationItem> occupations, ArrayList<PowerItem> superPowers) {

        this.BL = BL;
        this.gui = gui;
        gui.setEnabled(false);
        gui.setIsEnabled(false);
        
        this.addWindowListener(new WindowAdapter() {
        	public void windowClosing(java.awt.event.WindowEvent e) {
                gui.setIsEnabled(true);
                gui.setEnabled(true);
        	}
        });
        
        this.setSize(400, 400);
		this.setResizable(false);
		this.setIconImage(new ImageIcon(getClass().getResource("resources/windowIcon.gif")).getImage());

        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        
        String organizationsString = "";
        String occupationsString = "";
        String superPowersString = "";
        
        for (OrganizationItem organization : organizations)
        {
        	organizationsString = organizationsString.concat(organization.getName() + ", ");
        }
        if (!organizationsString.isEmpty())
        {
        	organizationsString = organizationsString.substring(0, organizationsString.length() - 2);
        }
        
        for (OccupationItem occupation : occupations)
        {
        	occupationsString = occupationsString.concat(occupation.getOccupation() + ", ");
        }
        if (!occupationsString.isEmpty())
        {
        	occupationsString = occupationsString.substring(0, occupationsString.length() - 2);
        }
        
        for (PowerItem power : superPowers)
        {
        	superPowersString = superPowersString.concat(power.getPower() + ", ");
        }
        if (!superPowersString.isEmpty())
        {
        	superPowersString = superPowersString.substring(0, superPowersString.length() - 2);
        }
        
        initFrame();
        initFields(gender, species, organizationsString, birthPlace, occupationsString, superPowersString);
    }

    private void initFrame() {

        mainPanel = new javax.swing.JPanel();
        headerLabel = new javax.swing.JLabel();
        genderLabel = new javax.swing.JLabel();
        speciesLabel = new javax.swing.JLabel();
        organizationLabel = new javax.swing.JLabel();
        birthplaceLabel = new javax.swing.JLabel();
        superPowersLabel = new javax.swing.JLabel();
        organizationTextField = new javax.swing.JTextField();
        superPowersTextField = new javax.swing.JTextField();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        occupationsLabel = new javax.swing.JLabel();
        occupationsTextField = new javax.swing.JTextField();
        
        java.awt.GridBagConstraints cons;        
        mainPanel.setLayout(new java.awt.GridBagLayout());
        mainPanel.setBackground(new Color(252, 251, 251));

        headerLabel.setText("EDIT INFORAMATION"); 
        headerLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
        cons = new java.awt.GridBagConstraints();
        cons.gridx = 0;
        cons.gridy = 0;
        cons.insets = new Insets(10, 20, 0, 10);
        cons.gridwidth = 2;
        cons.anchor = java.awt.GridBagConstraints.WEST;
        mainPanel.add(headerLabel, cons);
        
        genderLabel.setText("Gender: ");
        cons.gridwidth = 1;
        cons.gridy = 1;
        mainPanel.add(genderLabel, cons);
        
        speciesLabel.setText("Species: ");
        cons.gridy = 2;
        mainPanel.add(speciesLabel, cons);
        
        organizationLabel.setText("Organization: ");
        cons.gridy = 3;
        mainPanel.add(organizationLabel, cons);
        
        birthplaceLabel.setText("Birth Place: ");
        cons.gridy = 4;
        mainPanel.add(birthplaceLabel, cons);
        
        superPowersLabel.setText("Super Powers: ");
        cons.gridy = 5;
        mainPanel.add(superPowersLabel, cons);
        
        occupationsLabel.setText("Occupations: ");
        cons.gridy = 6;
        mainPanel.add(occupationsLabel, cons);
        
        cons = new java.awt.GridBagConstraints();
        cons.gridx = 1;
        cons.gridy = 1;
        cons.fill = GridBagConstraints.HORIZONTAL;
        cons.weightx = 1.0;
        cons.insets = new java.awt.Insets(10, 0, 0, 20);
        
        genders = BL.getAllGenders(new Response());
        genderComboBox = new javax.swing.JComboBox(genders.toArray());
        genderComboBox.setSelectedItem(null);
        mainPanel.add(genderComboBox, cons);
          
        species = BL.getAllSpecies(new Response());
        speciesComboBox = new javax.swing.JComboBox(species.toArray());
        speciesComboBox.setSelectedItem(null);
        cons.gridy = 2;
        mainPanel.add(speciesComboBox, cons);

        cons.gridy = 3;
        mainPanel.add(organizationTextField, cons);

        birthPlaces = BL.getAllPlaces(new Response());
        birthPlaceComboBox = new javax.swing.JComboBox(birthPlaces.toArray());
        birthPlaceComboBox.setSelectedItem(null);
        cons.gridy = 4;
        mainPanel.add(birthPlaceComboBox, cons);

        cons.gridy = 5;
        mainPanel.add(superPowersTextField, cons);
        
        cons.gridy = 6;
        mainPanel.add(occupationsTextField, cons);

        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridBagLayout());
        buttonsPanel.setBackground(new Color(252, 251, 251));

        okButton.setText("Update"); 
        okButton.setMaximumSize(new java.awt.Dimension(80, 23));
        okButton.setMinimumSize(new java.awt.Dimension(80, 23));
        okButton.setPreferredSize(new java.awt.Dimension(80, 23));
        okButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                okButtonMouseClicked(evt);
            }
        });
        
        cons = new java.awt.GridBagConstraints();
        cons.gridx = 0;
        cons.gridy = 0;
        cons.anchor = GridBagConstraints.CENTER;
        cons.insets = new java.awt.Insets(10, 30, 0, 30);
        buttonsPanel.add(okButton, cons);

        cancelButton.setText("Cancel"); 
        cancelButton.setMaximumSize(new java.awt.Dimension(80, 23));
        cancelButton.setMinimumSize(new java.awt.Dimension(80, 23));
        cancelButton.setPreferredSize(new java.awt.Dimension(80, 23));
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });
        cons = new java.awt.GridBagConstraints();
        cons.gridx = 1;
        cons.gridy = 0;
        cons.anchor = java.awt.GridBagConstraints.EAST;
        cons.insets = new java.awt.Insets(10, 30, 0, 30);
        buttonsPanel.add(cancelButton, cons);
        
        cons.gridx = 0;
        cons.gridy = 7;
        cons.gridwidth = 2;
        cons.insets = new java.awt.Insets(10, 0, 15, 0);
        cons.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(buttonsPanel, cons);
        
        this.add(mainPanel);

        pack();
    }

    private void okButtonMouseClicked(java.awt.event.MouseEvent evt) 
    {
    	if (validateAllFields())
    	{
    		gui.editInfo((GenderItem)genderComboBox.getSelectedItem(), (SpeciesItem)speciesComboBox.getSelectedItem(), organizationTextField.getText(), (PlaceItem)birthPlaceComboBox.getSelectedItem(), occupationsTextField.getText(), superPowersTextField.getText());
            gui.setIsEnabled(true);
            gui.setEnabled(true);
    		this.setVisible(false);
    		this.dispose();
    	}
    	else
    	{
    		JOptionPane.showMessageDialog(null, "Please only use letters, digits, underscores, whitespaces and commas (where allowed).", "Error Creating New User", JOptionPane.ERROR_MESSAGE);
    		return;
    	}
    }

    
    private boolean validateAllFields()
	{
    	if (!validateField(organizationTextField.getText(), true))
    	{
    		return false;
    	}
    	if (!validateField(occupationsTextField.getText(), true))
    	{
    		return false;
    	}
    	if (!validateField(superPowersTextField.getText(), true))
    	{
    		return false;
    	}
		return true;
	}

	private static boolean validateField(String fieldText, boolean allowCommas)
    {
    	char[] fieldChars = fieldText.toCharArray();
    	
    	for (int i = 0; i < fieldChars.length; i++)
    	{
    		char c = fieldChars[i];
    		if (c == ',')    			
    		{
    			if (!allowCommas)
    				return false;
    		}
    		else if (!Character.isLetter(c) && !Character.isDigit(c) && c != ' ' && c != '_')
    		{
    			return false;
    		}
    	}
    	
    	return true;
    }

    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) 
    {
        gui.setIsEnabled(true);
        gui.setEnabled(true);
        this.setVisible(false);
        this.dispose();
    }

    private void initFields(GenderItem gender, SpeciesItem species, String organization, PlaceItem birthPlace, String occupations, String superPowers) {
    	
    	for (GenderItem genderItem : genders)
    	{
    		if (genderItem.getId() == gender.getId())
    		{
    			genderComboBox.setSelectedItem(genderItem);
    			break;
    		}
    	}
    	
    	for (SpeciesItem speciesItem : this.species)
    	{
    		if (speciesItem.getId() == species.getId())
    		{
    			speciesComboBox.setSelectedItem(speciesItem);
    			break;
    		}
    	}
    	
    	if (organization != null)
    	{
    		organizationTextField.setText(organization);
    	}
    	
    	for (PlaceItem placeItem : birthPlaces)
    	{
    		if (placeItem.getId() == birthPlace.getId())
    		{
    			birthPlaceComboBox.setSelectedItem(placeItem);
    			break;
    		}
    	}
    	
    	if (occupations != null)
    	{
    		occupationsTextField.setText(occupations);
    	}
    	
    	if (superPowers != null)
    	{
    		superPowersTextField.setText(superPowers);
    	}
    }
    
    private javax.swing.JLabel birthplaceLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel genderLabel;
    private javax.swing.JLabel headerLabel;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel organizationLabel;
    private javax.swing.JTextField organizationTextField;
    private javax.swing.JLabel speciesLabel;
    private javax.swing.JLabel superPowersLabel;
    private javax.swing.JTextField superPowersTextField;
    private javax.swing.JLabel occupationsLabel;
    private javax.swing.JTextField occupationsTextField;
    private javax.swing.JComboBox genderComboBox;
    private javax.swing.JComboBox speciesComboBox;
    private javax.swing.JComboBox birthPlaceComboBox;

}